package com.a918.controller;

import com.a918.dto.TableResponse;
import com.a918.entity.*;
import com.a918.service.AnalyseService;
import com.a918.service.MemberService;
import com.a918.service.UserService;
import com.a918.util.FileUtil;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

@Controller
public class BackMemberController {

    private MemberService memberService;
    private UserService userService;
    private AnalyseService analyseService;

    @Autowired
    public BackMemberController(MemberService memberService, UserService userService, AnalyseService analyseService) {
        this.memberService = memberService;
        this.userService = userService;
        this.analyseService = analyseService;
    }

    @GetMapping("/register/{type}")
    public String register(@PathVariable(value="type",required=true)String type) {
        switch(type){
            //注册说明
            case "init":
                return "user/register_init";
            //选择类型
            case "type":
                return "user/register_type";
            //博物馆
            case "bwg":
                return "user/register_bwg";
            //个人
            case "per":
                return "user/register_per";
            //其他
            case "oth":
                return "user/register_oth";
            default:
                return null;
        }

    }

    //注册用户
    @PostMapping("/registerbwg")
    @ResponseBody
    public String registerbwg(User user, MemBwgWithBLOBs memBwgWithBLOBs, HttpServletRequest request) {
        String code = request.getParameter("code");
        String regcode  = (String) SecurityUtils.getSubject().getSession().getAttribute("CODE");

        if(!regcode.equals(code.toUpperCase())){
            return "codeError";
        }
        memberService.insertBwg(memBwgWithBLOBs);
        user.setUsertype(1);
        user.setOrderid(memBwgWithBLOBs.getId());
        userService.insertUser(user);
        memBwgWithBLOBs.setUserid(user.getId());
        memberService.updateBwg(memBwgWithBLOBs);
        return "success";
    }

    @PostMapping("/registerper")
    @ResponseBody
    public String registerper(User user, MemPerWithBLOBs memPerWithBLOBs, HttpServletRequest request) {
        String code = request.getParameter("code");
        String regcode  = (String) SecurityUtils.getSubject().getSession().getAttribute("CODE");
        if(!regcode.equals(code.toUpperCase())){
            return "codeError";
        }
        memberService.insertPer(memPerWithBLOBs);
        user.setUsertype(2);
        user.setOrderid(memPerWithBLOBs.getId());
        userService.insertUser(user);
        memPerWithBLOBs.setUserid(user.getId());
        memberService.updatePer(memPerWithBLOBs);
        return "success";
    }

    @PostMapping("/registeroth")
    @ResponseBody
    public String registeroth(User user, MemOth memOth, HttpServletRequest request) {
        String code = request.getParameter("code");
        String regcode  = (String) SecurityUtils.getSubject().getSession().getAttribute("CODE");
        if(!regcode.equals(code.toUpperCase())){
            return "codeError";
        }
        memberService.insertOth(memOth);
        user.setUsertype(3);
        user.setOrderid(memOth.getId());
        userService.insertUser(user);
        memOth.setUserid(user.getId());
        memberService.updateOth(memOth);
        return "success";
    }


    //数据查看
    @GetMapping("/memberlist/{type}")
    public String memberlist(@PathVariable(value="type",required=true)String type) {
        switch(type){
            //博物馆
            case "bwg":
                return "back/memlist_bwg";
            //个人
            case "per":
                return "back/memlist_per";
            //其他
            case "oth":
                return "back/memlist_oth";
            default:
                return null;
        }
    }
    @PostMapping("/getmemList/{type}")
    @ResponseBody
    public Object getmemList(@PathVariable(value="type",required=true)String type,@RequestParam Map<String, String> paramMap, HttpServletRequest request){
        switch(type){
            //博物馆
            case "bwg":
                PageInfo<MemBwg> pageInfo_bwg = memberService.findmemBwgList(paramMap);
                return new TableResponse(0,"查询成功", pageInfo_bwg.getList(),pageInfo_bwg.getTotal());
            //个人
            case "per":
                PageInfo<MemPer> pageInfo_per = memberService.findmemPerList(paramMap);
                return new TableResponse(0,"查询成功", pageInfo_per.getList(),pageInfo_per.getTotal());
            //其他
            case "oth":
                PageInfo<MemOth> pageInfo_oth = memberService.findmemOthList(paramMap);
                return new TableResponse(0,"查询成功", pageInfo_oth.getList(),pageInfo_oth.getTotal());
            default:
                return null;
        }
    }

    @GetMapping("/memberadd/{type}")
    public String memberadd(@PathVariable(value="type",required=true)String type) {
        switch(type){
            //博物馆
            case "bwg":
                return "back/memberadd_bwg";
            //个人
            case "per":
                return "back/memberadd_per";
            //其他
            case "oth":
                return "back/memberadd_oth";
            default:
                return null;
        }
    }

    //数据添加-提交
    @PostMapping("/submitbwg")
    @ResponseBody
    public String submitbwg(HttpServletRequest request,MemBwgWithBLOBs memBwgWithBLOBs){
        User user = userService.getUserByUsername((String) request.getSession().getAttribute("username"));
        user.setOrderid(memBwgWithBLOBs.getId());
        memBwgWithBLOBs.setUserid(user.getId());
        memBwgWithBLOBs.setCreattime(new Date());
        memBwgWithBLOBs.setAddress(memBwgWithBLOBs.getProvince()+"-"+memBwgWithBLOBs.getCity());
        memberService.insertBwg(memBwgWithBLOBs);

        Bwg2material material = new Bwg2material();
        material.setFileid(request.getParameter("fileid"));
        material.setFilename(request.getParameter("fileid"));
        material.setCreattime(new Date());
        material.setBwgid(memBwgWithBLOBs.getId());
        memberService.insertBwg2material(material);

        return "success_bwg";
    }

    @PostMapping("/submitper")
    @ResponseBody
    public String submitper(HttpServletRequest request,MemPerWithBLOBs memPerWithBLOBs){
        User user = userService.getUserByUsername((String) request.getSession().getAttribute("username"));
        user.setOrderid(memPerWithBLOBs.getId());
        memPerWithBLOBs.setUserid(user.getId());

        memberService.insertPer(memPerWithBLOBs);
        return "success_per";
    }

    @PostMapping("/submitoth")
    @ResponseBody
    public String submitoth(HttpServletRequest request,MemOth memOth){
        User user = userService.getUserByUsername((String) request.getSession().getAttribute("username"));
        user.setOrderid(memOth.getId());
        memOth.setUserid(user.getId());

        memberService.insertOth(memOth);
        return "success_oth";
    }

    //博物馆资料上传
    @PostMapping("/uploadbwg")
    @ResponseBody
    public Map uploadbwg(MultipartFile file){

        Map<String,Object> res=new HashMap<>();
        String uploadtag = FileUtil.uploadfile(file,"file//bwgfile");

        res.put("code",0);
        res.put("msg",0);
        res.put("originalName",file.getOriginalFilename());
        res.put("fileid",uploadtag);
        return res;

    }

    //数据分析
    @GetMapping("/analyse/{type}")
    public String analyse(@PathVariable(value="type",required=true)String type, Model model) {
        switch(type){
            //博物馆
            case "bwg":
                Map<String,Object> res = analyseService.bwgIndustryType();
                model.addAttribute("industryTypeName",res.get("industryTypeName"));
                model.addAttribute("industryTypeNum",res.get("industryTypeNum"));

                Map<String,Object> o2 = analyseService.bwgMuseumType();
                model.addAttribute("museumTypeName",o2.get("museumTypeName"));
                model.addAttribute("museumTypeNum",o2.get("museumTypeNum"));

                Map<String,Object> o3 = analyseService.bwgMainVistorType();
                model.addAttribute("mainvistorTypeName",o3.get("mainvistorTypeName"));
                model.addAttribute("mainvistorTypeNum",o3.get("mainvistorTypeNum"));

                Map<String,Object> o4 = analyseService.bwgFarenType();
                model.addAttribute("farenTypeName",o4.get("farenTypeName"));
                model.addAttribute("farenTypeNum",o4.get("farenTypeNum"));

                Map<String,Object> o5 = analyseService.bwgBuildingArea();
                model.addAttribute("buildingAreaNum",o5.get("buildingAreaNum"));

                return "back/analyse_bwg";
            //个人
            case "per":
                Map<String,Object> p1 = analyseService.perIndustryType();
                model.addAttribute("industryTypeName",p1.get("industryTypeName"));
                model.addAttribute("industryTypeNum",p1.get("industryTypeNum"));

                Map<String,Object> p2 = analyseService.perUnitType();
                model.addAttribute("unitTypeName",p2.get("unitTypeName"));
                model.addAttribute("unitTypeNum",p2.get("unitTypeNum"));

                Map<String,Object> p3 = analyseService.perXueLi();
                model.addAttribute("xueliName",p3.get("xueliName"));
                model.addAttribute("xueliNum",p3.get("xueliNum"));

                Map<String,Object> p4 = analyseService.perPoliticalStatus();
                model.addAttribute("politicalStatusName",p4.get("politicalStatusName"));
                model.addAttribute("politicalStatusNum",p4.get("politicalStatusNum"));

                return "back/analyse_per";
            //其他
            case "oth":
                Map<String,Object> h1 = analyseService.othIndustryType();
                model.addAttribute("industryTypeName",h1.get("industryTypeName"));
                model.addAttribute("industryTypeNum",h1.get("industryTypeNum"));

                Map<String,Object> h2 = analyseService.othUnitType();
                model.addAttribute("unitTypeName",h2.get("unitTypeName"));
                model.addAttribute("unitTypeNum",h2.get("unitTypeNum"));

                Map<String,Object> h3 = analyseService.othEmployeeNum();
                model.addAttribute("employeeNum",h3.get("employeeNum"));

                return "back/analyse_oth";
            default:
                return null;
        }
    }



    //已添加数据查看
    @GetMapping("/datashow/{type}")
    public String datashow(@PathVariable(value="type",required=true)String type) {
        switch(type){
            //博物馆
            case "bwg":
                return "back/datashow_bwg";
            //个人
            case "per":
                return "back/datashow_per";
            //其他
            case "oth":
                return "back/datashow_oth";
            default:
                return null;
        }
    }

    @PostMapping("/getinfo/{type}")
    @ResponseBody
    public Object getinfo(@PathVariable(value="type",required=true)String type,@RequestParam Map<String, String> paramMap, HttpServletRequest request){
        Integer userid = (Integer) request.getSession().getAttribute("id"),bwgid;
        switch(type){
            //博物馆
            case "bwg":
                PageInfo<MemBwg> pageInfo_bwg = memberService.getBwgInfo(paramMap,userid);
                return new TableResponse(0,"查询成功", pageInfo_bwg.getList(),pageInfo_bwg.getTotal());            //个人
            case "per":
                PageInfo<MemPer> pageInfo_per = memberService.getPerInfo(paramMap,userid);
                return new TableResponse(0,"查询成功", pageInfo_per.getList(),pageInfo_per.getTotal());
            //其他
            case "oth":
                PageInfo<MemOth> pageInfo_oth = memberService.getOthInfo(paramMap,userid);
                return new TableResponse(0,"查询成功", pageInfo_oth.getList(),pageInfo_oth.getTotal());
            //藏品
            case "cangpin":
                bwgid = Integer.valueOf(request.getParameter("bwgid"));
                PageInfo<Bwg2wenwu> cangpin = memberService.getCangpinInfo(paramMap,bwgid);
                return new TableResponse(0,"查询成功", cangpin.getList(),cangpin.getTotal());
            //政府支持
            case "ZFzhichi":
                bwgid = Integer.valueOf(request.getParameter("bwgid"));
                PageInfo<Bwg2govern> ZFzhichi = memberService.getZFzhichiInfo(paramMap,bwgid);
                return new TableResponse(0,"查询成功", ZFzhichi.getList(),ZFzhichi.getTotal());
            default:
                return null;
        }
    }

    @PostMapping("/deleteinfo/{type}")
    @ResponseBody
    public String deleteinfo(@PathVariable(value="type",required=true)String type,Integer id){
        switch(type){
            //博物馆
            case "bwg":
                try{
                    List<Bwg2wenwu> cangpinList = memberService.getCangpinListByBwgid(id);
                    List<String> picidList = new ArrayList<>();
                    for(Bwg2wenwu cangpin:cangpinList){  //删除相关藏品
                        memberService.deleteCangpinById(cangpin.getId());
                        picidList.add(cangpin.getPicid());
                    }
                    FileUtil.deleteCPpicture(picidList);//删除藏品图片

                    List<Bwg2govern> ZFzhichiList = memberService.getZFzhichiByBwgid(id);
                    for (Bwg2govern ZFzhichi:ZFzhichiList){ //删除相关政府支持情况
                        memberService.deleteZFzhichiById(ZFzhichi.getId());
                    }
                    List<Bwg2material> materialList = memberService.getMaterialLisiByBwgid(id);
                    FileUtil.deleteMaterial(materialList);
                    for(Bwg2material material:materialList){
                        memberService.deleteMaterialById(material.getId());//删除文件列表，记录
                    }
                    memberService.deleteBwgById(id);//删除men_bwg表中信息
                    return "success";
                }catch (Exception e){
                    return "error";
                }
            case "per":
                try{
                    memberService.deletePerById(id);
                    return "success";
                }catch (Exception e){
                    return "error";
                }
            case "oth":
                try{
                    memberService.deleteOthById(id);
                    return "success";
                }catch (Exception e){
                    return "error";
                }
            case "cangpin":
                try{
                    System.out.println(111);
                    System.out.println(id);
                    Bwg2wenwu cangpin = memberService.getCangpinById(id);
                    List<String> picidList = new ArrayList<>();
                    picidList.add(cangpin.getPicid());
                    FileUtil.deleteCPpicture(picidList);
                    memberService.deleteCangpinById(id);
                    return "success";
                }catch (Exception e){
                    return "error";
                }
            case "zfzhichi":
                try{
                    memberService.deleteZFzhichiById(id);
                    return "success";
                }catch (Exception e){
                    return "error";
                }
            default:
                return "error";
        }


    }

    @GetMapping("/xiangqing")
    public String xiangqing(HttpServletRequest request, Model model){
        String type = request.getParameter("type");
        String page = request.getParameter("page");
        model.addAttribute("page",page);
        Integer id = Integer.valueOf(request.getParameter("id"));
        switch(type){
            //博物馆
            case "bwg":
                MemBwgWithBLOBs bwg = memberService.getBwgInfoById(id);
                List<Bwg2material> materialList = memberService.getMaterialLisiByBwgid(id);
                String fileaddress = null;
                fileaddress = materialList.get(0).getFileid();
                model.addAttribute("bwg",bwg);
                model.addAttribute("fileaddress",fileaddress);
                return "back/xiangqing_bwg";
            //个人
            case "per":
                MemPerWithBLOBs per = memberService.getPerInfoById(id);
                model.addAttribute("per",per);
                return "back/xiangqing_per";
            //其他
            case "oth":
                MemOth oth = memberService.getOthInfoById(id);
                model.addAttribute("oth",oth);
                return "back/xiangqing_oth";
            //藏品List
            case "cangpinlist":
                model.addAttribute("bwgid",id);
                model.addAttribute("name",request.getParameter("name"));
                return "back/cangpinlist";
            //政府支持情况list
            case "ZFzhichilist":
                model.addAttribute("bwgid",id);
                model.addAttribute("name",request.getParameter("name"));
                return "back/ZFzhichilist";
            default:
                return null;
        }
    }

    @PostMapping("/xqmodify_bwg/{type}")
    @ResponseBody
    public String xqmodify_bwg(@PathVariable(value="type",required=true)String type,HttpServletRequest request, MemBwgWithBLOBs memBwgWithBLOBs) throws IOException {
        Integer userid = (Integer) request.getSession().getAttribute("id");

        memberService.updateBwg(memBwgWithBLOBs);
        Integer bwgid = memBwgWithBLOBs.getId();

        if(type.equals("chakan")) {
            String fileid = request.getParameter("fileid");

            List<Bwg2material> materialList = memberService.getMaterialLisiByBwgid(bwgid);
            if (materialList.size() > 0) {
                FileUtil.deleteMaterial(materialList);//删除原来的文件
                for (Bwg2material material : materialList) {
                    memberService.deleteMaterialById(material.getId());//删除文件列表，记录
                }
            }
            Bwg2material material = new Bwg2material();
            material.setFileid(fileid);
            material.setFilename(fileid);
            material.setCreattime(new Date());
            material.setBwgid(bwgid);
            memberService.insertBwg2material(material);//添加新的文件信息
        }else if(type.equals("register")){
            //更新用户状态
            User user =new User();
            user.setId(userid);
            user.setCheckstatus(1);
            userService.updateUserCheckstatus(user);


        }
        return "success_bwg";
    }

    @PostMapping("/xqmodify_per")
    @ResponseBody
    public String xqmodify_per(MemPerWithBLOBs memPerWithBLOBs) {
        memberService.updatePer(memPerWithBLOBs);
        return "success_per";
    }

    @PostMapping("/xqmodify_oth")
    @ResponseBody
    public String xqmodify_oth(MemOth memOth){
        memberService.updateOth(memOth);
        return "success_oth";
    }

    @GetMapping("/registerinfo/{page}")
    public String registerinfo(@PathVariable(value="page",required=true)String page,HttpServletRequest request, Model model) {
        Integer userid = null;
        if (page.equals("register")){
            userid = (Integer) request.getSession().getAttribute("id");//从注册资料进时
            System.out.println(22);
        }else if (page.equals("check")){
            userid = Integer.valueOf(request.getParameter("id"));//从注册审核进时
            System.out.println(11);

        }
        model.addAttribute("page", page);

        User user = userService.getUserById(userid);
        Integer usertype = user.getUsertype();

        //取审核文件
        if (page.equals("check")){
            List<RegisterFile> registerFileList = memberService.getRiRegisterFileByUserId(userid);
            model.addAttribute("file1", registerFileList.get(0));
            model.addAttribute("file2", registerFileList.get(0));
            if (registerFileList.size()>1){
                model.addAttribute("file2", registerFileList.get(1));
            }
        }

        switch (usertype) {
            //博物馆
            case 1:
                MemBwgWithBLOBs bwg = memberService.selectBwgId(userid);
                model.addAttribute("bwg", bwg);
                return "back/registerinfo_bwg";
            //个人
            case 2:
                MemPerWithBLOBs per = memberService.selectPerId(userid);
                model.addAttribute("per", per);
                return "back/registerinfo_per";
            //其他
            case 3:
                MemOth oth = memberService.selectOthId(userid);
                model.addAttribute("oth", oth);
                return "back/registerinfo_oth";
            default:
                return "error";
        }
    }

    @PostMapping("/addZFzhichi")
    @ResponseBody
    public String addZFzhichi(Bwg2govern bwg2govern){
        bwg2govern.setCreattime(new Date());
        try{
            memberService.insertBwgTogovern(bwg2govern);
            return "success";
        }catch (Exception e){
            return "error";
        }

    }

    @PostMapping("/addCangpin")
    @ResponseBody
    public String addCangpin(Bwg2wenwu bwg2wenwu) throws IOException {
        bwg2wenwu.setCreattime(new Date());
        try{
            memberService.insertBwg2wenwu(bwg2wenwu);
            return "success";
        }catch (Exception e){
            List<String> picidList = new ArrayList<>();
            picidList.add(bwg2wenwu.getPicid());
            FileUtil.deleteCPpicture(picidList);
            return "error";
        }

    }

    @ResponseBody
    @RequestMapping("/uploadCPpicture")
    public Map uploadCPpicture(MultipartFile file, HttpServletRequest request){

        Map<String,Object> res=new HashMap<>();
        res.put("code",0);
        res.put("msg",0);

        String uploadtag = FileUtil.uploadfile(file,"image//cangpin");
        res.put("data",uploadtag);
        return res;
    }

    @GetMapping("/uploadcheckfile")
    public String uploadcheckfile() {
        return "back/uploadcheckfile";
    }


    @ResponseBody
    @RequestMapping("/uploadredoc")
    public Map uploadregisterinfo(MultipartFile file, HttpServletRequest request){
        Integer userid = (Integer) request.getSession().getAttribute("id");
        List<RegisterFile> registerFileList = userService.getRegisterFileByUserid(userid);
        Map<String,Object> res=new HashMap<>();
        res.put("code",0);
        try{
            //填新的记录之前先删已有的文件和记录
            if(registerFileList.size()>0){
                for(RegisterFile registerFile:registerFileList){
                    FileUtil.deleteRegisterFile(registerFile.getFileid());
                    userService.deleteRegisterFileById(registerFile.getId());
                }
            }
        }catch (Exception e){
            res.put("code",1);
            res.put("msg","error");
            res.put("data","error");
            return res;
        }
        String uploadtag = FileUtil.uploadfile(file,"file//registerfile");
        if(!uploadtag.equals("fileTypeError") && !uploadtag.equals("existError") && !uploadtag.equals("error")){
            //更新registerfile表
            RegisterFile registerFile= new RegisterFile();
            registerFile.setUserid(userid);
            registerFile.setFileid(uploadtag);
            userService.insertRegisterFile(registerFile);

            //更新user表
            User user = new User();
            user.setId(userid);
            user.setCheckstatus(1);
            userService.updateCheckstatus(user);
            res.put("msg","success");

            res.put("data",uploadtag);
            return res;
        }else{
            res.put("code",1);
            res.put("msg","error");
            res.put("data","error");
            return res;
        }
    }


}

